import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import routes from './routes'
Vue.use(VueRouter)

const router = new VueRouter({
  routes
})
//解决重复点击导航时，控制台出现报错
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
      return VueRouterPush.call(this, to).catch(err => err)
}

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('accessToken')
  if (to.name !== 'login') {
    if (token) {
      store.dispatch('getUserInfo')
      next()
    } else {
      next('/login')
    }
  } else {
    if (token) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
